package com.jiaquyun.jcps.ui.main

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jiaquyun.jcps.R
import com.jiaquyun.jcps.base.ViewModeFragment
import com.jiaquyun.jcps.entity.OrderListEntity
import com.jiaquyun.jcps.mode.vm.MainViewModel
import com.jiaquyun.jcps.popup.ConfirmCancelPopup
import com.jiaquyun.jcps.ui.LoadingDialog
import com.lemlin.network.HttpServiceStatus
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.fragment_main.*
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream


class MainGiveFragment : ViewModeFragment<MainViewModel>() {

    private val giveAdapter =
        object : BaseQuickAdapter<OrderListEntity, BaseViewHolder>(R.layout.item_order_give) {
            init {
                addChildClickViewIds(
                    R.id.ivGiveNavigation,
                    R.id.tvGiveContactClient,
                    R.id.tvGiveConfirmService
                )
            }

            override fun convert(holder: BaseViewHolder, item: OrderListEntity) {
                holder.setText(R.id.tvGiveOrderNo, "#${item.order_no}")
                    .setText(R.id.tvGiveAddressCollect, item.end_address)
                    .setText(
                        R.id.tvGiveRangeCollect,
                        StringBuilder().append(item.distance).append("m")
                    )
                    .setText(
                        R.id.tvGiveRemarks,
                        StringBuilder().append("订单备注：").append(item.user_note)
                    )
            }
        }
    private val confirmCancelPopup: ConfirmCancelPopup by lazy {
        ConfirmCancelPopup(
            context = requireContext(),
            onConfirm = { any: Any?, action: ConfirmCancelPopup.Action? ->
                confirmCancelPopup.dismiss()
                if (action == null)
                    return@ConfirmCancelPopup
                if (action == ConfirmCancelPopup.Action.CONFIRM_GIVE) {
                    val rxPermissions = RxPermissions(requireActivity())
                    rxPermissions.request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                    ).subscribe {
                        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                        startActivityForResult(intent, (100))
                    }
                }
            },
            onCancel = { any: Any?, action: ConfirmCancelPopup.Action? ->
                confirmCancelPopup.dismiss()
            })
    }

    companion object {
        fun newInstance(): MainGiveFragment {
            return MainGiveFragment()
        }
    }

    override fun viewModel(): MainViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main

    private var position: Int = 0

    override fun initView() {
        rvMainBody.adapter = giveAdapter

        giveAdapter.setOnItemChildClickListener { adapter, view, position ->
            this.position = position
            val itemData: OrderListEntity = giveAdapter.getItem(position)
            when (view.id) {
                R.id.tvGiveContactClient -> {
                    viewModel.callPhone(itemData.mobile)
                }
                R.id.tvGiveConfirmService -> {
                    confirmCancelPopup.setMessage("确认已经送达客户手中或指定配送地点？")
                        .setAction(ConfirmCancelPopup.Action.CONFIRM_GIVE)
                        .setAny(itemData.id)
                        .showPopupWindow()
                }
                R.id.ivGiveNavigation -> {
                    Route2Activity.open(activity = requireActivity(), orderId = itemData.id)
                }
            }
        }

        smartRefreshHeader.setColorSchemeResources(R.color.colorMain)

        smartRefreshLayout.setOnRefreshListener {
            viewModel.orderListTab()
            viewModel.orderListGive()
        }
    }

    override fun initData() {
        smartRefreshLayout.autoRefresh()
    }

    override fun initViewMode() {
        viewModel.orderGiveLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                smartRefreshLayout.finishRefresh(false)
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                smartRefreshLayout.finishRefresh()
                response.httpData?.data?.let {
                    giveAdapter.setList(it)
                }
            }
        })
        viewModel.photoLiveData.observe(viewLifecycleOwner, Observer { response ->

            if (response.statusCode == HttpServiceStatus.Status.START) {
                LoadingDialog.show(requireContext())
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                LoadingDialog.dismiss()
                response.httpData?.data?.let {
                    val itemData: OrderListEntity = giveAdapter.getItem(position)
                    viewModel.orderService(itemData.id.toString(), it.url)
                }
            }
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                LoadingDialog.dismiss()
                toast(response.statusTip)
            }
        })
    }


    private var photoFile: File? = null

    //相机点击事件:打开照相机（该方式获取到的图片是原图）
    private fun openPhoto() {
        val localPath: String =
            requireContext().applicationContext.filesDir.absolutePath + "/jiaquyun"
        val dir = File(localPath)
        if (!dir.exists())
            dir.mkdirs()
        photoFile = File(("${dir.path}/${System.currentTimeMillis()}.png"))
        photoFile?.let {
            if (!it.exists())
                it.createNewFile()
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            intent.putExtra(
                MediaStore.EXTRA_OUTPUT,
                getUriForFile(requireContext(), it)
            )
            startActivityForResult(intent, (100))
        }
    }

    private fun getUriForFile(context: Context, file: File): Uri =
        if (Build.VERSION.SDK_INT >= 24) {
            FileProvider.getUriForFile(
                context, ("${context.packageName}.fileprovider"), file
            )
        } else Uri.fromFile(file)


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == AppCompatActivity.RESULT_OK && requestCode == 100) {
            try {
                val bitmap: Bitmap? = data?.extras?.get("data") as? Bitmap
//                val path: String = Environment.getExternalStorageDirectory().toString()
                val path: String = requireContext().applicationContext.filesDir.absolutePath
                var outStream: OutputStream? = null
                val file = File(path, "${System.currentTimeMillis()}.png")
                outStream = FileOutputStream(file)
                bitmap?.compress(Bitmap.CompressFormat.PNG, 100, outStream)
                outStream.close()
                viewModel.uploadImage(file.path)
//                toast("图像保存成功！")
            } catch (e: Exception) {
//                outStream?.close()
                toast("图像保存失败！${e.message}")
            }
        }
    }
}